package Pet.Management.controller;

import Pet.Management.domain.PetCareOffer;
import Pet.Management.service.PetCareOfferService;
import Pet.Management.domain.entity.PetDemand;
import Pet.Management.service.PetDemandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/pet-care/offers")
public class PetCareOfferController {

    @Autowired
    private PetCareOfferService petCareOfferService;

    @Autowired
    private PetDemandService petDemandService;

    @GetMapping("/my-accepts/{acceptorId}")
    public ResponseEntity<?> getMyAcceptOffers(
            @PathVariable Long acceptorId,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<PetCareOffer> offers = petCareOfferService.getOffersByAcceptorId(acceptorId);
            
            // 如果指定了状态，进行过滤
            if (status != null && !status.isEmpty()) {
                offers = offers.stream()
                    .filter(offer -> status.equals(offer.getStatus()))
                    .toList();
            }
            
            // 分页处理
            int start = page * size;
            int end = Math.min(start + size, offers.size());
            
            // 准备返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("total", offers.size());
            result.put("currentPage", page);
            result.put("pageSize", size);
            result.put("totalPages", (offers.size() + size - 1) / size);
            
            if (start >= offers.size()) {
                result.put("records", List.of());
            } else {
                result.put("records", offers.subList(start, end));
            }
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取接单列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/my-demands/{userId}")
    public ResponseEntity<?> getMyDemandOffers(
            @PathVariable Long userId,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<PetCareOffer> offers = petCareOfferService.getOffersByDemandUserId(userId);
            
            // 如果指定了状态，进行过滤
            if (status != null && !status.isEmpty()) {
                offers = offers.stream()
                    .filter(offer -> status.equals(offer.getStatus()))
                    .toList();
            }
            
            // 分页处理
            int start = page * size;
            int end = Math.min(start + size, offers.size());
            
            // 准备返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            Map<String, Object> data = new HashMap<>();
            data.put("offers", start >= offers.size() ? List.of() : offers.subList(start, end));
            data.put("totalItems", offers.size());
            result.put("data", data);
            result.put("msg", "获取数据成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", "获取需求报价失败: " + e.getMessage());
            return ResponseEntity.ok(error);
        }
    }

    @PostMapping
    public ResponseEntity<?> createOffer(@RequestBody PetCareOffer offer) {
        try {
            // 基本验证
            if (offer.getDemandId() == null) {
                return ResponseEntity.badRequest().body("需求ID不能为空");
            }
            if (offer.getAcceptorId() == null) {
                return ResponseEntity.badRequest().body("接单者ID不能为空");
            }
            if (offer.getServiceStartTime() == null || offer.getServiceEndTime() == null) {
                return ResponseEntity.badRequest().body("服务时间不能为空");
            }
            if (offer.getServiceEndTime().isBefore(offer.getServiceStartTime())) {
                return ResponseEntity.badRequest().body("服务结束时间不能早于开始时间");
            }
            if (offer.getPrice() == null || offer.getPrice().doubleValue() <= 0) {
                return ResponseEntity.badRequest().body("价格必须大于0");
            }

            // 获取需求信息
            PetDemand demand = petDemandService.getDemandById(offer.getDemandId());
            if (demand == null) {
                return ResponseEntity.badRequest().body("需求不存在");
            }

            // 设置需求发布者ID
            offer.setDemandUserId(demand.getUserId());
            
            // 设置创建时间
            offer.setCreatedAt(LocalDateTime.now());
            
            // 设置初始状态
            if (offer.getStatus() == null) {
                offer.setStatus("pending");
            }

            // 从需求中复制宠物信息（如果前端没有提供）
            if (offer.getPetName() == null) {
                offer.setPetName(demand.getPetName());
            }
            if (offer.getPetType() == null) {
                offer.setPetType(demand.getPetType());
            }
            if (offer.getPetAge() == null) {
                offer.setPetAge(demand.getPetAge());
            }
            if (offer.getPetGender() == null) {
                offer.setPetGender(demand.getPetGender());
            }

            return ResponseEntity.ok(petCareOfferService.createOffer(offer));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("接单失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<PetCareOffer> updateOffer(@PathVariable Long id, @RequestBody PetCareOffer offer) {
        offer.setId(id);
        return ResponseEntity.ok(petCareOfferService.updateOffer(offer));
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<?> updateOfferStatus(
            @PathVariable Long id, 
            @RequestBody(required = false) Map<String, String> statusMap,
            @RequestParam(required = false) String status) {
        try {
            // 首先尝试从请求体获取状态
            String statusValue = null;
            if (statusMap != null && statusMap.containsKey("status")) {
                statusValue = statusMap.get("status");
            }
            
            // 如果请求体中没有状态，则尝试从查询参数获取
            if (statusValue == null || statusValue.isEmpty()) {
                statusValue = status;
            }
            
            // 验证状态值
            if (statusValue == null || statusValue.isEmpty()) {
                throw new IllegalArgumentException("状态不能为空");
            }
            
            PetCareOffer offer = petCareOfferService.getOfferById(id);
            if (offer == null) {
                throw new IllegalArgumentException("未找到对应的报价记录");
            }
            
            offer.setStatus(statusValue);
            PetCareOffer updatedOffer = petCareOfferService.updateOffer(offer);
            
            // 返回与前端期望一致的响应格式
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("data", updatedOffer);
            result.put("msg", "状态更新成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", "更新状态失败: " + e.getMessage());
            return ResponseEntity.ok(error); // 返回200状态码但包含错误信息
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteOffer(@PathVariable Long id) {
        petCareOfferService.deleteOffer(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<PetCareOffer> getOfferById(@PathVariable Long id) {
        return ResponseEntity.ok(petCareOfferService.getOfferById(id));
    }

    @GetMapping("/demand/{demandId}")
    public ResponseEntity<List<PetCareOffer>> getOffersByDemandId(@PathVariable Long demandId) {
        return ResponseEntity.ok(petCareOfferService.getOffersByDemandId(demandId));
    }

    @GetMapping("/acceptor/{acceptorId}")
    public ResponseEntity<List<PetCareOffer>> getOffersByAcceptorId(@PathVariable Long acceptorId) {
        return ResponseEntity.ok(petCareOfferService.getOffersByAcceptorId(acceptorId));
    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<PetCareOffer>> getOffersByDemandUserId(
            @PathVariable Long userId) {
        return ResponseEntity.ok(petCareOfferService.getOffersByDemandUserId(userId));
    }

    @GetMapping("/status/{status}")
    public ResponseEntity<List<PetCareOffer>> getOffersByStatus(@PathVariable String status) {
        return ResponseEntity.ok(petCareOfferService.getOffersByStatus(status));
    }

    @GetMapping
    public ResponseEntity<List<PetCareOffer>> getAllOffers() {
        return ResponseEntity.ok(petCareOfferService.getAllOffers());
    }
} 